package org.atovio.problem.handler;

import org.atovio.problem.exception.BookNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.net.URI;
import java.time.Instant;
import java.time.LocalDateTime;

/**
 * @author AtoVio, Winter Yuan
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BookNotFoundException.class)
    public ProblemDetail handleBookNotFoundException(BookNotFoundException e) {

        // 创建ProblemDetail对象
        ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());

        // type 注明异常类型的URI。意思是，我们应该将解决办法设置在该URI资源中，以供用户查看
        problemDetail.setType(URI.create("/api/problems/not-found"));

        // 设置title
        problemDetail.setTitle("查询不到指定书籍");

        // 增加自定义字段
        problemDetail.setProperty("time", LocalDateTime.now());
        problemDetail.setProperty("call", "12138");

        return problemDetail;
    }
}
